package com.ysxsoft.wdg.ui.activity.home;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.classic.common.MultipleStatusView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.ysxsoft.wdg.R;
import com.ysxsoft.wdg.adapter.home.TbkAdapter;
import com.ysxsoft.wdg.base.BaseActivity;
import com.ysxsoft.wdg.base.BaseGWebViewActivity;
import com.ysxsoft.wdg.bean.response.HomeProductResponse;
import com.ysxsoft.wdg.bean.response.HomeVideoBean;
import com.ysxsoft.wdg.bean.response.TeachWenResponse;
import com.ysxsoft.wdg.net.CallbackCode;
import com.ysxsoft.wdg.net.UrlHost;
import com.ysxsoft.wdg.util.BigDecimalUtil;
import com.ysxsoft.wdg.util.JsonUtils;
import com.ysxsoft.wdg.util.ViewUtils;
import com.ysxsoft.wdg.util.WebViewUtils;
import com.ysxsoft.wdg.util.transform.FastSpeedLinearLayoutManager;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class NewActivity extends BaseActivity {


    @BindView(R.id.topView)
    View topView;
    @BindView(R.id.tv_video)
    TextView tvVideo;
    @BindView(R.id.tv_word)
    TextView tvWord;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.multStatusView)
    MultipleStatusView multStatusView;
    @BindView(R.id.ll_refresh)
    LinearLayout llRefresh;
    @BindView(R.id.webView)
    WebView webView;
    VedioAdapter adapter;
    TextAdapter adapter2;
    private int page = 1;
    LinearLayoutManager linearLayoutManager;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_new;
    }

    @Override
    protected void initData() {
        initStatusBar(topView, false);
        tvVideo.setSelected(true);
        WebViewUtils.init(webView);
        initRecyclerView();
        getVedioList();
    }

    private void initRecyclerView() {
        linearLayoutManager = new LinearLayoutManager(this);
        recyclerview.setLayoutManager(linearLayoutManager);
    }

    /**
     *
     */
    private void showText() {
        if (adapter2 == null) {
            adapter2 = new TextAdapter(R.layout.item_home_txt);
        }
        recyclerview.setNestedScrollingEnabled(false);
        recyclerview.setFocusable(false);
        recyclerview.setAdapter(adapter2);
        adapter2.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                TeachWenResponse.DataBean d= (TeachWenResponse.DataBean) adapter.getItem(position);
                BaseGWebViewActivity.start(NewActivity.this,d.getTitle(),d.getContent());
            }
        });
    }

    private void showVedio() {
        adapter = new VedioAdapter(R.layout.item_home_video);
        recyclerview.setNestedScrollingEnabled(false);
        recyclerview.setFocusable(false);
        recyclerview.setAdapter(adapter);
        recyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {
            int firstVisibleItem, lastVisibleItem;

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                firstVisibleItem = linearLayoutManager.findFirstVisibleItemPosition();
                lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
                //大于0说明有播放
                if (GSYVideoManager.instance().getPlayPosition() >= 0) {
                    //当前播放的位置
                    int position = GSYVideoManager.instance().getPlayPosition();
                    //对应的播放列表TAG
                    if (GSYVideoManager.instance().getPlayTag().equals(VedioAdapter.TAG)
                            && (position < firstVisibleItem || position > lastVisibleItem)) {
                        //如果滑出去了上面和下面就是否，和今日头条一样
                        if (!GSYVideoManager.isFullState(NewActivity.this)) {
                            GSYVideoManager.releaseAllVideos();
                            adapter.notifyDataSetChanged();
                        }
                    }
                }
            }
        });
    }

    @Override
    protected void setListener() {
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                if (isVideo) {
                    getVedioList();
                } else {
                    getTextDetail();
                }
            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                page++;
                if (isVideo) {
                    getVedioList();
                } else {
                    getTextDetail();
                }
            }
        });
    }

    @OnClick({R.id.title_finish, R.id.tv_video, R.id.tv_word})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_finish:
                finish();
                break;
            case R.id.tv_video:
                tvVideo.setSelected(true);
                tvWord.setSelected(false);
                recyclerview.setVisibility(View.VISIBLE);
                webView.setVisibility(View.GONE);
                llRefresh.setVisibility(View.VISIBLE);
                isVideo = true;
                page = 1;
                getVedioList();
                break;
            case R.id.tv_word:
                tvVideo.setSelected(false);
                tvWord.setSelected(true);
                recyclerview.setVisibility(View.VISIBLE);
                webView.setVisibility(View.GONE);
                llRefresh.setVisibility(View.VISIBLE);
                isVideo = false;
                page = 1;
                getTextDetail();
                break;
        }
    }

    private boolean isVideo = false;

    /**
     * 获取新手指南文本
     */
    private void getTextDetail() {
        if (page == 1) {
            multStatusView.showLoading();
        }
        OkHttpUtils.post()
                .url(UrlHost.NOVICE_TEXT)
                .addParams("page", page + "")
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                    reset();
                }
            }

            @Override
            public void onResponse(String response, int id) {
                multStatusView.showContent();
                reset();
                if (response != null) {
                    TeachWenResponse teachWenResponse = JsonUtils.parseByGson(response, TeachWenResponse.class);
                    if (teachWenResponse == null) {
                        return;
                    }
                    List<TeachWenResponse.DataBean> list = teachWenResponse.getData();
                    if (CallbackCode.SUCCESS.equals(teachWenResponse.getCode())) {
                        if (page == 1) {
                            showText();
                            adapter2.setNewData(list);
                        } else {
                            adapter2.addData(list);
                        }
                    } else {
                        if (page == 1) {
                            if (list != null && !list.isEmpty()) {
                            } else {
                                multStatusView.showEmpty();
                            }
                        }
                    }
                } else {
                }
            }
        });
    }

    /**
     * 获取视频
     */
    private void getVedioList() {
        if (page == 1) {
            multStatusView.showLoading();
        }
        OkHttpUtils.post()
                .url(UrlHost.NOVICE_VEDIO)
                .addParams("page", page + "")
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                    multStatusView.showError();
                    reset();
                }
            }

            @Override
            public void onResponse(String response, int id) {
                reset();
                if (response != null) {
                    HomeVideoBean homeProductResponse = JsonUtils.parseByGson(response, HomeVideoBean.class);
                    if (homeProductResponse == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(homeProductResponse.getCode())) {
                        List<HomeVideoBean.DataBean> list = homeProductResponse.getData();
                        if (page == 1) {
                            showVedio();
                            multStatusView.showContent();
                            if (list != null && !list.isEmpty()) {
                            } else {
                                multStatusView.showEmpty();
                            }
                            adapter.setNewData(list);
                        } else {
                            adapter.addData(list);
                        }
                    }
                } else {
                    multStatusView.showError();
                }
            }
        });
    }

    private void reset() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.finishRefresh(true);
        }
        refreshLayout.finishLoadmore();
    }

    /**
     * 视频适配器
     */
    private class VedioAdapter extends BaseQuickAdapter<HomeVideoBean.DataBean, BaseViewHolder> {
        public final static String TAG = "VideoAdapter";

        public VedioAdapter(int layoutResId) {
            super(layoutResId);
        }

        public void clear() {
            getData().clear();
            notifyDataSetChanged();
        }

        @Override
        protected void convert(BaseViewHolder helper, HomeVideoBean.DataBean item) {
            ImageView logo = helper.getView(R.id.logo);
            Glide.with(NewActivity.this).load(item.getAvatar()).into(logo);

            ImageView iv_cover = helper.getView(R.id.iv_cover);
            Glide.with(NewActivity.this).load(item.getPic()).into(iv_cover);
            helper.setText(R.id.tv_title, item.getName());
            helper.setText(R.id.tv_content, item.getTitle());
            helper.setText(R.id.tv_num, item.getHit());

            RelativeLayout relativeLayout = helper.getView(R.id.pic);
            relativeLayout.setOnClickListener(new OnPicClickListener(item.getContent()));
        }

        private class OnPicClickListener implements View.OnClickListener {
            private String url;

            public OnPicClickListener(String url) {
                this.url = url;
            }

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(NewActivity.this, DetailControlActivity.class);
                intent.putExtra("url", url);
                startActivity(intent);
            }
        }
    }


    /**
     * 文字适配器
     */
    private class TextAdapter extends BaseQuickAdapter<TeachWenResponse.DataBean, BaseViewHolder> {

        public TextAdapter(int layoutResId) {
            super(layoutResId);
        }

        public void clear() {
            getData().clear();
            notifyDataSetChanged();
        }

        @Override
        protected void convert(BaseViewHolder helper, TeachWenResponse.DataBean item) {
            ImageView logo = helper.getView(R.id.logo);
            Glide.with(NewActivity.this).load(item.getAvatar()).into(logo);

            TextView name = helper.getView(R.id.name);
            name.setText(item.getName());
            helper.setText(R.id.time, item.getAddtime());
            helper.setText(R.id.content, item.getTitle());
        }
    }

}
